package cn.zhy.user.service.impl;

import cn.zhy.basic.constants.VerifyCodeConstants;
import cn.zhy.basic.exception.BusinessException;
import cn.zhy.basic.jwt.JwtUtils;
import cn.zhy.basic.jwt.LoginData;
import cn.zhy.basic.jwt.RsaUtils;
import cn.zhy.basic.util.AjaxResult;
import cn.zhy.basic.util.HttpUtil;
import cn.zhy.basic.util.MD5Utils;
import cn.zhy.basic.util.StrUtils;
import cn.zhy.system.domain.Menu;
import cn.zhy.system.mapper.MenuMapper;
import cn.zhy.system.mapper.PermissionMapper;
import cn.zhy.user.constant.WxConstants;
import cn.zhy.user.domain.Logininfo;
import cn.zhy.user.domain.User;
import cn.zhy.user.domain.Wxuser;
import cn.zhy.user.dto.LoginDto;
import cn.zhy.user.mapper.LogininfoMapper;
import cn.zhy.user.mapper.UserMapper;
import cn.zhy.user.mapper.WxuserMapper;
import cn.zhy.user.service.ILogininfoService;
import cn.zhy.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;



    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer type = loginDto.getType();
        //校验空值
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password) ){
            throw new BusinessException("请输入合法信息!!!");
        }

        //校验账号-账号可以是手机号-名字-邮箱等等所以要写一个方法
        Logininfo  logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null){
            throw new BusinessException("账号错误!!!");
        }

        //校验账号密码是否正确
        //3.校验 - 校验密码
        String password1 = logininfo.getPassword();//数据库中加密的密码
        String salt = logininfo.getSalt();
        String md5 = MD5Utils.encrypByMd5(password + salt);
        if (!md5.equals(password1)){
            throw new BusinessException("密码错误!!!");
        }
//        //4.状态校验 - 启用，禁用
//        if(!logininfo.getDisable()){
//            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
//        }
//
//        //4.生成key【token】 将key和登录信息对象保存到redis
//        String token = UUID.randomUUID().toString();
//        //去掉密码盐值-因为要返回到页面储存
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("logininfo",logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }


    public Map<String ,Object> loginSuccessJwtHandler(Logininfo logininfo){
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            if (logininfo.getType()==0){//管理员
                //获取当前登录人的权限
                List<String> permissions = permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
                //3.获取当前登陆人的所有菜单
                List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
                //将 permission  menus  logininfo 设置进去  和logindate里的数据对应
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                //将当前登陆人的权限和菜单添加到map - 响应给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }

            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().
                    getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);
            //5.装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    @Override
    public AjaxResult wechat(String code) {
        //1.准备发送第二个请求的参数：
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        //2.发送请求 - 返回json格式的数据
        String jsonStr = HttpUtil.httpGet(url);

        //3.将json格式的数据转成json对象 - 为了获取里面的token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //4.通过openid查询数据库
        Wxuser wxuser = wxuserMapper.loadByOpenid(openId);

        //4.1.查询到了并且user_id有值 = 以前绑定过 = 直接免密登录
        if(wxuser!=null && wxuser.getUserId()!=null && userMapper.loadById(wxuser.getUserId())!=null){
            //免密登录 = 不需要通过页面输入账号密码就直接登录：token，logininfo
            //4.登录成功将登录信息保存在redis - 方便后续判断时候已经登陆过
            String token = UUID.randomUUID().toString();//jsessionid

            User user = userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

            //这个数据要响应给前端 - 所以为了安全置空
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//            //5.响应信息，并且将token【后续判断登录】和logininfo【显示用户名】响应给前端
//            Map<String,Object> map = new HashMap<>();
//            map.put("token",token);
//            map.put("logininfo",logininfo);
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            //6.响应数据
            return AjaxResult.me().setResultObj(map);
        }else{
            //4.2.没有查询到响应给前端进行跳转 = 设置success=false，并且将token和openid传递给前端
            String param = "?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.me().setSuccess(false).setResultObj(param);
        }
    }

    //微信绑定
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        //空值校验
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空!!!");
        }
            //校验验证码是否过期
            Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);

            if (obj == null) {
                throw new BusinessException("验证码过期!!!");
            }
            //redis保存的验证码和用户输入的是否一致
            if (!obj.toString().split(":")[0].equals(verifyCode)) {
                throw new BusinessException("验证码错误!!!");

            }

            //通过ack和openid发送第三个请求-在WxConstants里获取
            String url = WxConstants.GET_ACK_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("OPENID", openId);
            //发送请求 - 返回json格式的数据
            String jsonStr = HttpUtil.httpGet(url);
            //处理响应的数据：json字符串 - json对象 - 获取wxUser的信息
            Wxuser wxuser = jsonStr2Wxuser(jsonStr);

            //绑定用户：将WxUser对象【第三个请求中获取】 与 User对象【通过手机创建】进行绑定
            //先查询用户手机号
            User user = userMapper.loadByPhone(phone);
            //如果根据电话没有查询到user表里的数据就根据电话创建一个user对象添加到数据库
            if (user == null) {
                //通过phone创建User对象
                user = phone2User(phone);
                Logininfo logininfo = user2Logininfo(user);
                logininfoMapper.save(logininfo);
                user.setLogininfoId(logininfo.getId());
                userMapper.save(user);

            }
            //user一定会有。并且user_id也有
            wxuser.setUserId(user.getId());
            wxuserMapper.save(wxuser);

            //做免密登录：token，logininfo对象
//            String token = UUID.randomUUID().toString();
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
//         logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//            Map<String, Object> mapTemp = new HashMap<>();
//            mapTemp.put("token", token);
//            mapTemp.put("logininfo", logininfo);
        Map<String, Object> mapTemp = loginSuccessJwtHandler(logininfo);
            return new AjaxResult().setResultObj(mapTemp);
        }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setUsername(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机密码
        String ranPwd = StrUtils.getComplexRandomString(6);
        String md5 = MD5Utils.encrypByMd5(ranPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        user.setState(1);
        return user;

    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        //将json字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //必须和wxuser数据库字段一样
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");

        wxuser.setAddress(country+province+city);
        return wxuser;
    }


}

